<template>
    <div class="nvb_tabs">
        <swiper :slides-per-view="slidesPerView" class="mySwiper">
            <swiper-slide v-for="(item, index) in tabList" :key="item.name">
                <span
                    :class="{ nvb_tab: true, active: route.name === item.name }"
                    @click="clickTab(item)"
                    @click.middle="closeTab(item)"
                >
                    {{ item.title }}
                    <IconClose
                        v-if="item.name !== 'dashboard'"
                        @click.stop="closeTab(item)"
                    ></IconClose>
                </span>
            </swiper-slide>
        </swiper>

        <span class="nvb_tab close_all_tab" @click="closeAllTab">全部关闭</span>
    </div>
</template>

<script setup lang="ts">
import { IconClose } from '@arco-design/web-vue/es/icon'
import { ref, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'
import { Swiper, SwiperSlide } from 'swiper/vue'
import type { ITab } from '@/types'

const route = useRoute()
const router = useRouter()

const slidesPerView = ref(13)
onMounted(() => {
    //总宽度
    const mySwiperWith = document.querySelector('.mySwiper')
    //实际宽度
    const actualWith = document.querySelector('.swiper-wrapper').scrollWidth
    if (actualWith <= mySwiperWith) {
        return
    }

    const swiperSlideList = document.querySelectorAll(
        '.swiper-wrapper .swiper-slide',
    )

    let sum = 0
    let count = 0

    for (const slide of swiperSlideList) {
        sum += slide.clientWidth
        if (sum > mySwiperWith) {
            break
        }
        count++
    }
    slidesPerView.value = count
})

const tabList = ref<ITab[]>([{ name: 'dashboard', title: '仪表盘' }])

function clickTab(item) {
    router.push({ name: item.name })
}

//持久化存储
function persistence() {
    sessionStorage.setItem('tabList', JSON.stringify(tabList.value))
}

function loadTabs() {
    const val = sessionStorage.getItem('tabList')
    if (val === null) {
        return false
    }
    tabList.value = JSON.parse(val)
}

loadTabs()

watch(
    () => tabList.value.length,
    () => {
        persistence()
    },
)

function closeAllTab() {
    if (tabList.value.length === 1) return false
    tabList.value = tabList.value.filter((i) => i.name === 'dashboard')
    router.push({ name: 'dashboard' })
}

function closeTab(item: ITab) {
    if (item.name === 'dashboard') return false
    const idx = tabList.value.findIndex((i) => i.name === item.name)
    if (route.name === item.name) {
        tabList.value.splice(idx, 1)
        router.push({ name: tabList.value[idx - 1].name })
    } else {
        tabList.value.splice(idx, 1)
    }
}

const isList = (name: string): boolean => {
    return JSON.stringify(tabList).includes(name)
}

watch(
    () => route.name,
    () => {
        if (!isList(route.name as string)) {
            //当前路由不在列表中，则添加
            tabList.value.push({
                name: route.name as string,
                title: route.meta.title as string,
            })
        }
    },
    { immediate: true },
)
</script>

<style lang="scss">
.nvb_tabs {
    height: 30px;
    width: 100%;
    border-bottom: 1px solid var(--bg);
    padding: 0 20px;
    display: flex;
    align-items: center;
    position: relative;
    background-color: var(--color-bg-1);

    .mySwiper {
        width: calc(100% - 94px);
        overflow: hidden;
        white-space: nowrap;
        height: 100%;
        display: flex;
        align-items: center;

        .swiper-wrapper {
            display: flex;
            justify-content: start;
            width: 100%;

            .swiper-slide {
                width: auto !important;
            }
        }
    }

    .nvb_tab {
        border-radius: 5px;
        border: 1px solid var(--bg);
        padding: 2px 8px;
        margin-right: 10px;
        cursor: pointer;

        &.active {
            background-color: var(--active);
            color: #fff;
            border: none;

            svg:hover {
                background-color: rgb(var(--arcoblue-4));
            }
        }

        svg {
            font-size: 12px;
            transition: all 0.3s ease-out;
            border-radius: 50px;

            &:hover {
                background-color: var(--bg);
            }
        }
    }

    .close_all_tab {
        position: absolute;
        right: 20px;
        margin-right: 0;
    }
}
</style>
